#!/usr/bin/python

import sys, os
import scapy
import re

class MacVendorFinder:

    def __init__(self, mac="00:00:00:00:00:00", vendor_list='built-in'):
        self.mac = mac.lower()
        self.vendor = 'Unknown'
        self.serial = self.mac[:9]
        self.searched = False
        self.vendor_list = vendor_list

    def __get_vendor_list(self):
        if self.vendor_list == 'built-in':
            return self.get_builtin_vendor_list()
        else:
            f = self.vendor_list
            if not os.path.isfile(f):
                raise IOError("File %s does not exist" % self.vendor_list)
            fin = open(f, 'r')
            l = fin.readlines()
            fin.close()
            return l

    def get_builtin_vendor_list(self):
        import etherdb
        return etherdb.VENDOR_NAMES.split('\n')
        

    def find(self):
        if re.match(r"^([0-9a-f]{2}:){5}([0-9a-f]{2})$", self.mac) is None:
            raise ValueError("Invalid MAC address") 
        self.serial = self.mac[9:]
        for line in self.__get_vendor_list():
            # discard empty lines
            if line.strip() == '':
                continue
            tokens = line.split("-")
            desc = ""
            if len(tokens) > 3:
                #vendor contains '-' characters, fix it
                for i in tokens[2:]:
                    desc += "%s " % str(i)
            else:
                desc = tokens[2]
                
            if self.mac[:8] == tokens[1].strip():
                self.vendor = desc.strip()
        #fin.close()
        self.searched = True

    # Check if the given MAC vendor contains the vendor_string
    # i.e. self.is_from("Apple")
    def is_from(self, vendor_string):
        if not self.searched:
            self.find()
        if self.vendor.lower().find(vendor_string.lower()) != -1:
            return True
        return False

    def get_vendor_match(self, vendor_name):
        if vendor_name == None:
            raise Error("Vendor name is None.")
        matches = []
        for i in self.__get_vendor_list():
            if i.lower().find(vendor_name.lower()) != -1:
                matches.append (i)
        return matches
		



class MacHunter:

    # If range is not provided use first interface
    # and it's Mask to do the scan
    def __init__(self, range):
        pass

    # Return a list of host that replied to the arp request
    def scan(self):
        pass
